import { Ref, ref, onMounted } from 'vue'
import lottie, { AnimationItem, AnimationConfigWithPath, AnimationConfigWithData } from 'lottie-web'

type LottieOptions =
    | Omit<AnimationConfigWithPath, 'container'>
    | Omit<AnimationConfigWithData, 'container'>
export default function (
    container: Ref<HTMLElement | null | undefined>,
    options: LottieOptions,
    onSuccess?: (instance: AnimationItem) => void
): Ref<AnimationItem> {
    const lottieInstance = ref<AnimationItem>() as Ref<AnimationItem>
    onMounted(() => {
        if (!container.value) return
        lottieInstance.value = lottie.loadAnimation({
            container: container.value as HTMLElement,
            loop: true,
            renderer: 'svg',
            autoplay: true,
            ...options
        })
        if (onSuccess) onSuccess(lottieInstance.value as AnimationItem)
    })
    return lottieInstance
}
